package com.amigo.online.provider.ffmpeg.config;

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import feign.form.ContentType;
import feign.form.MultipartFormContentProcessor;
import feign.form.spring.SpringFormEncoder;
import feign.form.spring.SpringManyMultipartFilesWriter;
import feign.form.spring.SpringSingleMultipartFileWriter;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Map;

/**
 * amigo-online-consumer-video /video/upload/video接口专用
 * 其他接口使用可能出现问题
 * 如果需要,建议重写
 * @author 庞冬皓
 */
public class SpringFormEncoderExtension extends SpringFormEncoder {

    /**
     * 使用默认的feign编码器
     *
     * @author*/
    public SpringFormEncoderExtension() {
        this(new Default());
    }

    /**
     * 使用传入的编码器并提供对多文件的支持
     *
     * @param encoder 编码器
     * @author*/
    public SpringFormEncoderExtension(Encoder encoder) {
        super(encoder);

        MultipartFormContentProcessor processor = (MultipartFormContentProcessor) getContentProcessor(ContentType.MULTIPART);
        processor.addWriter(new SpringSingleMultipartFileWriter());
        processor.addWriter(new SpringManyMultipartFilesWriter());
    }

    /**
     * 模仿FormEncode对其进行扩展支持多文件传递
     *
     * @param object   传递内容
     * @param bodyType 传递类型
     * @param template 传递路径
     * @author*/
    @Override
    public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        if (bodyType.equals(MultipartFile.class)) {
            template.header("Content-Type","multipart/form-data");
            MultipartFile file = (MultipartFile) object;
            Map data = Collections.singletonMap(file.getName(), object);
            super.encode(data, MAP_STRING_WILDCARD, template);
        } else if (bodyType.equals(MultipartFile[].class)) {
            template.header("Content-Type","multipart/form-data");
            MultipartFile[] file = (MultipartFile[]) object;
            if (file != null) {
                Map data = Collections.singletonMap(file.length == 0 ? "" : "files", object);
                super.encode(data, MAP_STRING_WILDCARD, template);
            }
        } else {
            super.encode(object, bodyType, template);
        }
    }
}
